package com.dragon.loan.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dragon.account.repository.PrCodeTableRepository;
import com.dragon.loan.common.Constants;
import com.dragon.loan.entity.AcLoanApplyInfo;
import com.dragon.loan.entity.AcUserBank;
import com.dragon.loan.entity.CommonParam;
import com.dragon.loan.entity.CommonParamItem;
import com.dragon.loan.repository.AcLoanApplyInfoRepository;
import com.dragon.loan.repository.AcUserBankMapper;

import cn.hutool.core.util.StrUtil;

@Service
public class AcUserBankServiceImpl implements AcUserBankDragonService {

	@Autowired
	private AcUserBankMapper acUserBankMapper;
	@Autowired
	private AcLoanApplyInfoRepository acLoanApplyInfoRepository;
	@Autowired
	private GetCommonParamIService getCommonParamIService;
	@Autowired
	private PrCodeTableRepository prCodeTableRepository;
	@Override
	public Integer insert(AcUserBank acUserBank) {
		acUserBankMapper.insertSelective(acUserBank);
		return acUserBank.getId();
	}
	
	@Deprecated  
	@Override
	public List<Map<String, Object>> listAcUserBankByUserId(String userId) {
		return acUserBankMapper.listAcUserBankByUserId(userId);
	}
	
	/*@Override
	public List<Map<String, Object>> listAcUserBankByIdentityCardNo(String IdentityCardNo, String userId) {
		String loanId = acLoanApplyInfoRepository.selectCustApplyingLoanId(IdentityCardNo);
		if(StringUtils.isEmpty(loanId)) return acUserBankMapper.listAcUserBankByUserId(userId);
		AcLoanApplyInfo loan = acLoanApplyInfoRepository.findByLoanId(loanId);
		List<Map<String, Object>> listAcUserBankByUserId = acUserBankMapper.listAcUserBankByUserId(userId);
		// ☆ 鉴于云展业的目前还款卡跟放款卡都是一样的，所以只要判断其中一个就可以了
		if(loan != null && ("1".equals(loan.getProductType() + "") || "4".equals(loan.getProductType() + "") || "8".equals(loan.getProductType() + "")) && StringUtils.isNotEmpty(loan.getRepayAcct())){
			//1 还款卡   
			if(listAcUserBankByUserId == null) listAcUserBankByUserId = new ArrayList<>();
			String repayAcct = loan.getRepayAcct();
			String mobileNum = loan.getMobileNum();
			saveBankCard(repayAcct, listAcUserBankByUserId, userId, loan.getRepayBankName(), "借记卡", mobileNum);
		}
		
		// 放款卡     2
		String receiveAcct = loan.getReceiveAcct();
		// 还款卡      1         如果同时又是还款卡 又是放款卡 3
		String repayAcct = loan.getRepayAcct();
		boolean hasReceiveAcct = false;
		boolean hasRepayAcct = false;
		if(StringUtils.isNotEmpty(repayAcct) && StringUtils.isNotEmpty(receiveAcct)){
			for (Map<String, Object> map : listAcUserBankByUserId) {
				if(map == null) continue;
				Object object = map.get("bankCardNo");
				if(object == null) continue;
				String card = (String)object;
				if(receiveAcct.equals(card) && !hasReceiveAcct){
					hasReceiveAcct = true;
					if(repayAcct.equals(receiveAcct)) {
						map.put("isDefaulet", "3");
						break;
					}
					map.put("isDefaulet", "2");
					continue;
				}
				if(repayAcct.equals(card) && !hasRepayAcct){
					hasRepayAcct = true;
					map.put("isDefaulet", "1");
					continue;
				}
			}
		}
		return listAcUserBankByUserId;
	}*/

	@Override
	public List<Map<String, Object>> listAcUserBankByIdentityCardNo(String IdentityCardNo, String loanId) {
		List<Map<String, Object>> listAcUserBankByIdCard = acUserBankMapper.listAcUserBankByIdCard(IdentityCardNo);
		AcLoanApplyInfo loan = acLoanApplyInfoRepository.findByLoanId(loanId);
		if(!StrUtil.isEmpty(loanId)){
			String fundId = acLoanApplyInfoRepository.selectFundSourceByLoanId(loanId);
			// 首先根据fundId 查出对应的商户号出来然后判断卡列表是不是符合打标记
			String merNoByFundId = getMerNoByFundId(fundId);
			// 放款卡     2
			String receiveAcct = loan.getReceiveAcct();
			// 还款卡      1         如果同时又是还款卡 又是放款卡 3
			String repayAcct = loan.getRepayAcct();
			boolean hasReceiveAcct = false;
			boolean hasRepayAcct = false;
			if(StrUtil.isNotEmpty(repayAcct) && StrUtil.isNotEmpty(receiveAcct)){
				for (Map<String, Object> map : listAcUserBankByIdCard) {
					if(map == null) continue;
					if(map.get("contractNo") != null){
						if(map.get("merNo") != null){
							if(map.get("merNo").toString().equals(merNoByFundId)){
								map.put("isValid", "1");
							}else{
								map.put("isValid", "0");
							}
						}else if(map.get("merNo") == merNoByFundId){
							map.put("isValid", "1");
						}else{
							map.put("isValid", "0");
						}
					}else{
						map.put("isValid", "0");
					}
					Object object = map.get("bankCardNo");
					if(object == null) continue;
					String card = (String)object;
					if(receiveAcct.equals(card) && !hasReceiveAcct){
						hasReceiveAcct = true;
						if(repayAcct.equals(receiveAcct)) {
							map.put("isDefaulet", "3");
							break;
						}
						map.put("isDefaulet", "2");
						continue;
					}
					if(repayAcct.equals(card) && !hasRepayAcct){
						hasRepayAcct = true;
						map.put("isDefaulet", "1");
						continue;
					}
				}
			}
		}
		// 去重银行卡
		Map<String, Map<String, Object>> resultMap = new HashMap<String, Map<String, Object>>();
		for(Map<String, Object> acUserBank : listAcUserBankByIdCard){
			String bankCardNo = acUserBank.get("bankCardNo").toString();
			Object contractNoObj = acUserBank.get("contractNo");
			Object merNoObj = acUserBank.get("merNo");
			Map<String, Object> bankMap = resultMap.get(bankCardNo);
			if(bankMap == null){
				resultMap.put(bankCardNo, acUserBank);
				continue;
			}
			// 下面就是 bankMap != null
			Object isValidObj = acUserBank.get("isValid");
			Object isDefauletObj = acUserBank.get("isDefaulet");
			if(isValidObj != null && "1".equals(isValidObj.toString())){
				bankMap.put("isValid", "1");
			}
			if(isDefauletObj != null && ("1".equals(isDefauletObj.toString()) || "2".equals(isDefauletObj.toString()) || "3".equals(isDefauletObj.toString()))){
				bankMap.put("isDefaulet", isDefauletObj.toString());
			}
			
			// 做这个操作的目的
			// 因为有很多张卡但是不知道使用哪个卡的ID (去重前会有多个卡ID)
			if(loan != null && contractNoObj != null){
				String fundSource = acLoanApplyInfoRepository.selectFundSourceByLoanId(loanId);
				 if(fundSource != null){
					 String merNoByFundId = getMerNoByFundId(fundSource.toString());
					 if(merNoByFundId == null){
						 if(merNoObj == null) bankMap.put("id", acUserBank.get("id"));
					 }else if(merNoObj != null && merNoByFundId.toString().equals(merNoObj.toString())){
						 bankMap.put("id", acUserBank.get("id"));
					 }
				 }
			}
		}
		return new ArrayList<Map<String, Object>>(resultMap.values());
	}
	
	@Override
	public AcUserBank selectByPrimaryKey(Integer id) {
		if(id == null || id <= 0) return null; 
		return acUserBankMapper.selectByPrimaryKey(id);
	}

	@Override
	public AcUserBank queryByBankCardNum(String bankCardNum) {
		return acUserBankMapper.queryByBankCardNum(bankCardNum);
	}
	
	@Override
	public boolean hasRepetitionBankCard(String bankCardNo, String userId) {
		
		return false;
	}
	
	// ---------------------------------------------------------------------------------------------------------
	private void saveBankCard(String bankCard, List<Map<String, Object>> listAcUserBankByUserId, String userId, String bankName, String bankType, String mobileNum){
		// 判断已有的卡列表中是否含有这个还款卡
		boolean hasThisReceiveAcct = false;
		for (Map<String, Object> map : listAcUserBankByUserId) {
			String bankCardNo = (String)map.get("bankCardNo");
			if(bankCardNo.equals(bankCard)) {
				hasThisReceiveAcct = true;
				continue;
			}
		}
		// 如果不包含就把这张卡加入卡列表中
		if(!hasThisReceiveAcct){
			AcUserBank acUserBank = new AcUserBank();
			acUserBank.setBankCardNo(bankCard);
			acUserBank.setBankCardType(bankType);
			acUserBank.setBankName(bankName);
			acUserBank.setUserId(userId);
			acUserBank.setMobileNum(mobileNum);
			acUserBank.setBankCode("yyyy");
			acUserBank.setCreatedBy("system");
			int bankCardId = acUserBankMapper.insertSelective(acUserBank);
			
			// 添加到这个list集合中  避免再次查库
			Map<String, Object> newCard = new HashMap<>();
			newCard.put("id", bankCardId);
			newCard.put("bankCardNo", acUserBank.getBankCardNo());
			newCard.put("bankName", acUserBank.getBankName());
			newCard.put("bankCardType", acUserBank.getBankCardType());
			newCard.put("mobileNum", mobileNum);
			listAcUserBankByUserId.add(newCard);
		}
	}
	/**
	 * 
	 * @Title: queryByCardNumAndUserId   
	 * @Description: 根据卡号和用户id查询客户银行卡信息 
	 * @param:      
	 * @return: AcUserBank      
	 * @throws
	 */
	@Override
	public AcUserBank queryByCardNumAndUserId(String bankCardNum, String userId) {
		return acUserBankMapper.queryByCardNumAndUserId(bankCardNum, userId);
	}
	
	
	/**
	 * 
	* @Title: queryByCardNumAndUserId 
	* @Description:根据身份证和卡号获取用户卡信息  
	* @param bankCardNum
	* @param idno
	* @return       
	* @author 李瑶
	* @date 2018年8月1日 下午3:33:31
	 */
	@Override
	public AcUserBank queryByCardNumAndIdno(String bankCardNum, String idno) {
		return acUserBankMapper.queryByCardNumAndIdno(bankCardNum, idno);
	}

	@Override
	public String getMerNoByFundId(String fundId) {
		if(StrUtil.isEmpty(fundId)) return null;
		CommonParam commonParam = getCommonParamIService.getCommonParam("FUND_MER_NO");
		if(commonParam == null) return null;
		List<CommonParamItem> commonParamItems = commonParam.getCommonParamItems();
		for (CommonParamItem commonParamItem : commonParamItems) {
			String itemId = commonParamItem.getItemId();
			if(fundId.equals(itemId)){
				return commonParamItem.getItemName();
			}
		}
		return null;
	}

	@Override
	public Boolean isNeedAgainBindCard(AcLoanApplyInfo acLoanApplyInfo) {
		String loanId = acLoanApplyInfo.getLoanId();
		String fundId = acLoanApplyInfoRepository.selectFundSourceByLoanId(loanId);
		String merNo = getMerNoByFundId(fundId);
		String repayAcct = acLoanApplyInfo.getRepayAcct();
		AcUserBank acUserBank = new AcUserBank();
		acUserBank.setMerNo(merNo);
		acUserBank.setBankCardNo(repayAcct);
		Long count = acUserBankMapper.countByMerNoBankCardNo(acUserBank);
		return count == null || count.intValue() <= 0;
	}
	
	public List<String> querySupportBank(String busType){
		String typeId = null;
		if("0".equals(busType))
			typeId = Constants.SUPPORTBANK_LOAN;
		else if("1".equals(busType))
			typeId = Constants.SUPPORTBANK_REPAYMENT;
		else if("2".equals(busType))
			typeId = Constants.SUPPORTBANK_CREDIT;
		return prCodeTableRepository.selectIdByTypeId(typeId);
	}

	@Override
	public List<AcUserBank> selectUserBankInfo(AcUserBank userBank) {
		return acUserBankMapper.selectUserBankInfo(userBank);
	}
}
